# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from io import BytesIO, StringIO
import csv

class PdExcel:
    def export(self):
        # 创建数据流
        buffer = BytesIO()
        # 创建excel work book
        writer = pd.ExcelWriter(buffer, engine='xlsxwriter')
        workbook = writer.book
        # 创建excel sheet
        worksheet = workbook.add_worksheet('sheet1')
        # cell 样式
        cell_format = workbook.add_format({
            'bold': True,  # 字体加粗
            'border': 1,  # 单元格边框宽度
            'align': 'left',  # 水平对齐方式
            'valign': 'vcenter',  # 垂直对齐方式
            'fg_color': '#F4B084',  # 单元格背景颜色
            'text_wrap': True  # 是否自动换行
        })

        col = 0
        row = 1
        # 写入列名
        columns = range(10000)
        for item in columns:
            worksheet.write(0, col, item, cell_format)
            col += 1
        # 写入数据
        index = 0
        while index < 10:
            for co in columns:
                worksheet.write(row, columns.index(co), index)
            row += 1
            index += 1
            print('row===%s,index===%s' % (row, index))
        # 设置A-E的宽
        worksheet.set_column('A:E', 20)

        writer.close()
        buffer.seek(0)
        return buffer


    def export_pd_csv(self):

        # 创建一个DataFrame
        data = {'name': ['John,nn', 'Mike,lll', 'Sarah'], 'age': [25, 30, 28]}
        df = pd.DataFrame(data)

        # 创建数据流
        buffer = BytesIO()

        # 将DataFrame写入CSV文件
        df.to_csv(buffer, index=False)

        buffer.seek(0)

        return buffer


    def export_csv(self):
        header = ['id', 'stu_id', 'course_name', 'course_score']
        data = [
            [1, 1, 'English', 100],
            [2, 1, 'Math', 95],
            [3, 2, 'English', 96]
        ]

        with open('score.csv', 'w', encoding='UTF8', newline='') as f:
            writer = csv.writer(f)
            # write the header
            writer.writerow(header)
            # write the data
            writer.writerows(data)
